import 'package:get/get.dart';
import 'package:kkhousekeep/models/notice_list_entity.dart';
import 'package:kkhousekeep/net/home_notice_connect.dart';
import 'package:kkhousekeep/net/respnse_code.dart';
import 'package:kkhousekeep/tools/dialog_util.dart';

import '../../../../tools/shared_preferences.dart';
import '../../../login/login_controller.dart';
import 'notice_detail_page.dart';

class NoticePageController extends GetxController {
  var noticeList = <NoticeListObjList>[].obs;
  late HomeNoticeConnect _homeNoticeConnect;

  @override
  void onInit() {
    _homeNoticeConnect = Get.put(HomeNoticeConnect());
    super.onInit();

    _loadNetworkData();
  }

  Future<void> _loadNetworkData() async {
    UserType userType = await getSp().getUserType();
    NoticeListEntity noticeListEntity;
    noticeListEntity = await _homeNoticeConnect.getNoticeList(
        isOwner: userType == UserType.owner);
    noticeList.value = noticeListEntity.obj.list;
  }

  Future<void> allRead() async {
    UserType userType = await getSp().getUserType();
    var response = await _homeNoticeConnect.noticeAllRead(
        isOwner: userType == UserType.owner);
    if (response == null) {
      return;
    }
    if (response.code == ResponseCode.success) {
      for (var element in noticeList) {
        element.read = 1;
      }
      noticeList.refresh();
      DialogUtil.showNetworkSucceed();
    } else {
      DialogUtil.showNetworkFail();
    }
  }

  void buildNoticeItem(NoticeListObjList noticeModel) {
    Get.to(() => const NoticeDetailPage(), arguments: noticeModel)
        ?.whenComplete(() {
      if (noticeModel.read == 0) {
        var noticePageController = Get.find<NoticePageController>();
        noticePageController.noticeList
            .firstWhere((element) => element == noticeModel)
            .read = 1;
        noticePageController.noticeList.refresh();
      }
    });
  }
}
